package org.rost.web.thrithon.core;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;

public class ThrithonAppContext {
    
    private String defaultPage = "";
    private List<String> extensions = new ArrayList<String>();
    private String templateDir = "";
    private ServletContext servletContext = null;
    private String actionPrefix = "";
    private List<BeanDefinition> beans = new ArrayList<BeanDefinition>();
    private List<FilterDefinition> filters = new ArrayList<FilterDefinition>();
    
    private List<ActionDefinition> actions = new ArrayList<ActionDefinition>();
    
    private static ThrithonAppContext instance = null;
    
    public static void log(String message){
        getContext().getServletContext().log(message);
    }
    
    public static ThrithonAppContext getContext(){
        if(instance==null)
            instance = new ThrithonAppContext();
        return instance;
    }

    public String getDefaultPage() {
        return defaultPage;
    }

    void setDefaultPage(String defaultPage) {
        this.defaultPage = defaultPage;
    }

    public List<String> getExtensions() {
        return extensions;
    }

    public ServletContext getServletContext() {
        return servletContext;
    }

    void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    List<BeanDefinition> getBeans() {
        return beans;
    }

    List<ActionDefinition> getActions() {
        return actions;
    }

    public String getTemplateDir() {
        return templateDir;
    }

    void setTemplateDir(String templateDir) {
        if(templateDir==null)
            templateDir = "";
        this.templateDir = templateDir;
    }

    public List<FilterDefinition> getFilters() {
        return filters;
    }
    
    public ThrithonFilter getFilter(String alias){
        for (FilterDefinition filterDefinition : filters) {
            if(filterDefinition.getAlias().equals(alias))
                return filterDefinition.getFilter();
        }
        return null;
    }
    
    public InputStream getResourceAsStream(String path, ThrithonRequestContext ctx){
        String p = getTemplateDir()+ctx.getCurrentDir()+path;
        if(path.startsWith("/"))
            p = getTemplateDir()+path;
//        EngineAppContext.log("Path = "+p);
        return getServletContext().getResourceAsStream(p);
    }

    public String getActionPrefix() {
        return actionPrefix;
    }

    void setActionPrefix(String actionPrefix) {
        this.actionPrefix = actionPrefix;
    }
}
